/*
 * @Author: lizhijie429
 * @Date: 2021-08-28 18:27:33
 * @LastEditors: lizhijie429
 * @LastEditTime: 2021-09-06 19:33:43
 * @Description:
 */

import axios from "axios";
import qs from "qs"; //处理参数
import { message } from "antd";
import httpConfig from "../config/index";

const http = axios.create();
http.defaults.baseURL = httpConfig.API_URL;

/* 请求拦截头 */
http.interceptors.request.use(
  function (config) {
    /* 设置统一的请求拦截头 */
    const AUTH_TOKEN = sessionStorage.getItem("token");
    if (AUTH_TOKEN) {
      config.headers.Authorization = AUTH_TOKEN;
    }
    return config;
  },
  function (error) {
    /* 抛出异常 */
    return Promise.reject(error);
  }
);

/* 响应拦截头 */
http.interceptors.response.use(
  function (response) {
    /* 统一的响应错误处理 */
    return response;
  },
  function (error) {
    /* 抛出异常 */
    return Promise.reject(error);
  }
);

//关闭加载动画
function closeLoading() {
  console.log("关闭加载动画");
}

function checkStatus(response) {
  return new Promise((resolve, reject) => {
    if (response && (response.status === 200 || response.status === 201)) {
      try {
        closeLoading(); //关闭加载动画
        resolve(response.data);
      } catch (e) {
        console.log(e); //抛出异常
        message.error("服务器端异常！");
      }
    } else if (response && response.status === 400) {
      try {
        closeLoading(); //关闭加载动画
        message.error("This is an error message");
      } catch (e) {
        console.log(e); //抛出异常
        message.error("服务器端异常！");
      }
    }
  });
}

/* get请求 */
export const getRequest = async (url, params) => {
  params = qs.stringify(params);
  const response = await http({
    url,
    method: "get",
    params,
  });
  return await checkStatus(response);
};

/* post请求 */
export const postRequest = async (url, params) => {
  const response = await http({
    url,
    method: "post",
    data: params,
  });
  return await checkStatus(response);
};
